package ans1;

/**
 * @author Dujie
 * @create 2025/8/7
 * @since 1.0.0
 */
import com.yirui.serialcomm.core.domain.ASN1SerialCommPacket;
import com.yirui.serialcomm.core.domain.StreamType;
import org.bouncycastle.asn1.*;
import java.io.*;

public class TypedByteArrayExample {

    public static void main(String[] args) throws IOException {
        // 准备测试数据
        byte[] data1 = "abc".getBytes();
        byte[] data2 = "123".getBytes();

        // 创建带类型的数据对象
        ASN1SerialCommPacket obj1 = new ASN1SerialCommPacket(StreamType.TCP, data1);
        ASN1SerialCommPacket obj2 = new ASN1SerialCommPacket(StreamType.UDP, data2);

        // ========== 编码 ==========
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ASN1OutputStream asn1Out = ASN1OutputStream.create(byteOut);
        try{
            asn1Out.writeObject(obj1);
            asn1Out.writeObject(obj2);
        }finally {
            asn1Out.close();
        }

        byte[] encodedData = byteOut.toByteArray();
        System.out.println("编码后的数据 (HEX): " + bytesToHex(encodedData));

        // ========== 解码 ==========
        ByteArrayInputStream byteIn = new ByteArrayInputStream(encodedData);
        try (ASN1InputStream asn1In = new ASN1InputStream(byteIn)) {
            // 解码第一个对象
            ASN1Primitive prim1 = asn1In.readObject();
            ASN1SerialCommPacket decoded1 = ASN1SerialCommPacket.getInstance(prim1);
            System.out.println("\n解码对象1:");
            System.out.println("类型: " + decoded1.getType());
            System.out.println("数据: " + new String(decoded1.getData()));

            // 解码第二个对象
            ASN1Primitive prim2 = asn1In.readObject();
            ASN1SerialCommPacket decoded2 = ASN1SerialCommPacket.getInstance(prim2);
            System.out.println("\n解码对象2:");
            System.out.println("类型: " + decoded2.getType());
            System.out.println("数据: " + new String(decoded2.getData()));
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString();
    }
}